package com.hcmiu.buddytracking;

import getFromDBMethods.getNewMessages;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import setMethods.setMessage;
import Utils.toastMaking;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MessageBoard extends Activity {
	private EditText msgboard;
	private EditText msg;
	private Button sendmsg;
	private SharedPreferences pref;
	private String PREF_NAME = "buddytracking";
	private ArrayList<Storage.Message> boardMessages = new ArrayList<Storage.Message>();
	private String currentPhoneNumber;
	private String lastMesssageID;
	private ProgressDialog progressDialog;
	private refreshMessageThread myThread = new refreshMessageThread();
	private int refresh_interval = 4*1000;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.messageboard);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Loading messages...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);

		pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
		currentPhoneNumber = pref.getString("currentPhoneNumber", "");
		lastMesssageID = "0";
		this.setTitle("Message Board");
		msgboard = (EditText) findViewById(R.id.msgboard);
		msgboard.setMovementMethod(new ScrollingMovementMethod());
		msg = (EditText) findViewById(R.id.textmsg);
		sendmsg = (Button) findViewById(R.id.sendmsgButton);
		msg.setHint("Tap to enter message");
		sendmsg.setOnClickListener(sendmsg());
		// myHandler.sendMessage(new Message());
		progressDialog.show();
		Thread t = new Thread() {			
			@Override			
			public void run() {
				myThread.run();				
			}			
		};
		t.start();
		progressDialog.dismiss();
		
	}

	private View.OnClickListener sendmsg() {
		return new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					if (msg.getText().toString().equals(""))
						toastMaking.errorToast(getApplicationContext(),
								"Empty messages are not allowed").show();
				
				else if (msg.getText().toString().length() > 100 )
				{
					toastMaking.errorToast(getApplicationContext(),
					"Shorten your message -  max 100 chars").show();
				}
					else {
						sendMessage(currentPhoneNumber, msg.getText()
								.toString());
						refreshMessageBoard();						
						msg.setText("");
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};

	}

	private void refreshMessageBoard() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("currentPhoneNumber", currentPhoneNumber);
		object.put("lastmsgid", lastMesssageID);
		boardMessages.clear();
		boardMessages = getNewMessages.process(object.toString());
		if (boardMessages.size() != 0) {
			appendMessages();
			lastMesssageID = (boardMessages.get(boardMessages
					.size() - 1).getMsgId());
		}
	}

	private void appendMessages() {
		for (Storage.Message aMessage : boardMessages) {
			msgboard.append(aMessage.getSenderName() + ": "
					+ aMessage.getMsgContent() + "\n");
		}		
	}

	private void sendMessage(String phoneNo, String message)
			throws JSONException {
		JSONObject object = new JSONObject();
		object.put("phonenumber", phoneNo);
		object.put("msgcontent", message);
		setMessage.process(object.toString());

	}

	class refreshMessageThread extends Thread {
		private boolean isRunning = false;
		private boolean isPaused = false;

		public void run() {
			isRunning = true;
			try {
				while (isRunning) {
					if (isPaused) {
						synchronized (this) {
							this.wait();
						}
					} else if (isPaused == false) {												
							myHandler.sendMessage(new Message());
							Thread.sleep(refresh_interval);						
					}
				}
			} catch (Exception ex) {
				// do stuff
			}
		}

		public void stopThread() {
			isRunning = false;
		}

		public void pauseThread() {
			isPaused = true;
		}

		public synchronized void resumeThread() {
			this.notify();
			isPaused = false;
		}

	}

	@Override
	public void onPause() {
		super.onPause();
		myThread.pauseThread();
		
	}
	@Override
	public void onResume() {
		super.onResume();		
		myThread.resumeThread();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		myThread.stopThread();
	}

	Handler myHandler = new Handler() {
		/** update friend's location on every msg received */

		@Override
		public void handleMessage(Message msg) {
			try {
				refreshMessageBoard();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
	};
}
